package com.dousb.cloudlibrary.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.constant.CommonConstant;
import com.dousb.cloudlibrary.exception.BusinessException;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.mapper.CommentMapper;
import com.dousb.cloudlibrary.model.dto.comment.CommentQueryRequest;
import com.dousb.cloudlibrary.model.entity.Comment;
import com.dousb.cloudlibrary.model.entity.User;
import com.dousb.cloudlibrary.model.vo.CommentVO;
import com.dousb.cloudlibrary.model.vo.UserVO;
import com.dousb.cloudlibrary.service.CommentService;
import com.dousb.cloudlibrary.service.UserService;
import com.dousb.cloudlibrary.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 评论表服务实现
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private UserService userService;

    @Resource
    private CommentMapper commentMapper;

    /**
     * 校验数据
     *
     * @param comment
     * @param add     对创建的数据进行校验
     */
    @Override
    public void validComment(Comment comment, boolean add) {
        ThrowUtils.throwIf(comment == null, ErrorCode.PARAMS_ERROR);
        //   从对象中取值
        String content = comment.getContent();
        String topic_type = comment.getTopic_type();

        // 创建数据时，参数不能为空
        if (add) {
            //   补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(topic_type), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        //   补充校验规则
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 10240, ErrorCode.PARAMS_ERROR, "评论内容过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param commentQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Comment> getQueryWrapper(CommentQueryRequest commentQueryRequest) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        if (commentQueryRequest == null) {
            return queryWrapper;
        }
        //   从对象中取值
        Long id = commentQueryRequest.getId();
        String content = commentQueryRequest.getContent();
        Long user_id = commentQueryRequest.getUser_id();
        Long topic_id = commentQueryRequest.getTopic_id();
        String topic_type = commentQueryRequest.getTopic_type();
        Long parent_id = commentQueryRequest.getParent_id();
        Long root_id = commentQueryRequest.getRoot_id();
        Integer like_count = commentQueryRequest.getLike_count();
        Integer reply_count = commentQueryRequest.getReply_count();
        String sortField = commentQueryRequest.getSortField();
        String sortOrder = commentQueryRequest.getSortOrder();

        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(user_id), "user_id", user_id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(topic_id), "topic_id", topic_id);
        queryWrapper.eq(StringUtils.isNotBlank(topic_type), "topic_type", topic_type);
        queryWrapper.eq(ObjectUtils.isNotEmpty(parent_id), "parent_id", parent_id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(root_id), "root_id", root_id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(like_count), "like_count", like_count);
        queryWrapper.eq(ObjectUtils.isNotEmpty(reply_count), "reply_count", reply_count);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取评论表封装
     *
     * @param comment
     * @param request
     * @return
     */
    @Override
    public CommentVO getCommentVO(Comment comment, HttpServletRequest request) {
        // 对象转封装类
        CommentVO commentVO = CommentVO.objToVo(comment);

        //   可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = comment.getUser_id();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        commentVO.setUser(userVO);
        return commentVO;
    }

    /**
     * 分页获取评论表封装
     *
     * @param commentPage
     * @param request
     * @return
     */
    @Override
    public Page<CommentVO> getCommentVOPage(Page<Comment> commentPage, HttpServletRequest request) {
        List<Comment> commentList = commentPage.getRecords();
        Page<CommentVO> commentVOPage = new Page<>(commentPage.getCurrent(), commentPage.getSize(), commentPage.getTotal());
        if (CollUtil.isEmpty(commentList)) {
            return commentVOPage;
        }
        // 对象列表 => 封装对象列表
        List<CommentVO> commentVOList = commentList.stream().map(comment -> {
            return CommentVO.objToVo(comment);
        }).collect(Collectors.toList());
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = commentList.stream().map(Comment::getUser_id).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        User loginUser = userService.getLoginUserPermitNull(request);
        // 填充信息
        commentVOList.forEach(commentVO -> {
            Long userId = commentVO.getUser_id();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            commentVO.setUser(userService.getUserVO(user));
        });
        commentVOPage.setRecords(commentVOList);
        return commentVOPage;
    }

    /**
     * 获取树形评论
     *
     * @param topic_id@return
     */
    @Override
    public List<CommentVO> getCommentTreeOptimized(Long topic_id, String topic_type, HttpServletRequest request) {
        ThrowUtils.throwIf(topic_id == null || topic_id <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(StringUtils.isBlank(topic_type), ErrorCode.PARAMS_ERROR);
        try {
            //1.查询主题下的所有的评论
            QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
            commentQueryWrapper.eq("topic_id", topic_id)
                    .eq("topic_type", topic_type)
                    .orderByAsc("create_time");
            List<Comment> commentList = commentMapper.selectList(commentQueryWrapper);

            if (ObjectUtils.isEmpty(commentList)) {
                return new ArrayList<>();
            }
            //2.批量查询用户信息
            Set<Long> userIds = commentList.stream()
                    .map(Comment::getUser_id)
                    .collect(Collectors.toSet());
            Map<Long, User> userMap = userService.listByIds(userIds).stream()
                    .collect(Collectors.toMap(User::getId, user -> user));
            //3.转换为vo并构建树形结构
            Map<Long, CommentVO> commentVOMap = new HashMap<>();
            List<CommentVO> rootComments = new ArrayList<>();
            for (Comment comment : commentList) {
                CommentVO commentVO = CommentVO.objToVo(comment);
                //设置用户信息
                User user = userMap.get(comment.getUser_id());
                if (user != null) {
                    UserVO userVO = userService.getUserVO(user);
                    commentVO.setUser(userVO);
                }
                commentVOMap.put(comment.getId(), commentVO);
            }
            for (Comment comment : commentList) {
                CommentVO currentVO = commentVOMap.get(comment.getId());
                Long parentId = comment.getParent_id();
                if (parentId == null || parentId <= 0) {
                    rootComments.add(currentVO);
                } else {
                    //子评论
                    CommentVO parentVO = commentVOMap.get(parentId);
                    if (parentVO != null) {
                        if (parentVO.getChildren() == null) {
                            parentVO.setChildren(new ArrayList<>());
                        }
                        parentVO.getChildren().add(currentVO);
                    }
                }
            }

            //对评论进行排序
            rootComments.sort((c1, c2) -> c2.getCreate_time().compareTo(c1.getCreate_time()));

            // 对每个根评论的子评论按时间正序排序（最早的回复在最前面）
            for (CommentVO rootComment : rootComments) {
                if (CollUtil.isNotEmpty(rootComment.getChildren())) {
                    rootComment.getChildren()
                            .sort((c1, c2) -> c1.getCreate_time().compareTo(c2.getCreate_time()));
                }
            }
            return rootComments;
        } catch (Exception e) {
            log.error("获取评论树失败, topicId: {}, topicType: {}", topic_id, topic_type, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取评论树失败");
        }
    }

}
